package com.morizhang.usersys.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.morizhang.usersys.api.ApiResult;
import com.morizhang.usersys.api.IService;
import com.morizhang.usersys.api.bean.ErrorDefinition;
import com.morizhang.usersys.api.bean.ErrorDefinitionHolder;
import com.morizhang.usersys.api.bean.UserSysException;
import com.morizhang.usersys.api.dao.BasicUserInfoDao;
import com.morizhang.usersys.api.model.UserModel;
import com.morizhang.usersys.api.service.IdentifyCheckService;
import com.morizhang.usersys.api.service.ServiceAnnotation;
import com.morizhang.usersys.api.utils.ErrorUtils;
import com.morizhang.usersys.api.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;

@ServiceAnnotation(name = "IdentifyCheck")
public class IdentifyCheckServiceImpl implements IdentifyCheckService, IService {

    @Autowired
    protected BasicUserInfoDao basicUserInfoDao;

    protected UserSysException userSysException;

    @Override
    public Boolean identifyUserByUserID(UserModel user) throws Exception {
        int result = basicUserInfoDao.checkUser(user);
        return result != 0;
    }

    @Override
    public ApiResult callService(JSONObject requestParams) throws Exception {
        ApiResult result = new ApiResult();
        JSONObject requestParamsData = requestParams.getJSONObject("data");
        try {
            UserModel user = new UserModel();
            user.setUserID(requestParamsData.getString("userID"));
            user.setUserName(requestParamsData.getString("userName"));
            user.setPassword(requestParamsData.getString("password"));
            //UserFormCheck
            if (!UserUtils.userFormCheck(user)) {
                ErrorDefinition error = ErrorDefinitionHolder.get("INVALID_CHECK_USER_FORM");
                userSysException = ErrorUtils.convertErrorToException(error);
                throw userSysException;
            }
            if (identifyUserByUserID(user)) {
                result.setSuccess(true);
                result.setData(true);
            } else {
                result.setSuccess(true);
                result.setData(false);
            }
            return result;
        } catch (UserSysException e) {
            result.setSuccess(false);
            result.setFaultMessage(e.getExceptionMessage());
            result.setException(e);
            return result;
        }
    }
}
